import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截，在每次请求之前
service.interceptors.request.use(
  config => {
    // 在每次请求之前的配置项
    // do something before request is sent
    // let each request carry token
    config.headers['Authorization'] = getToken()
    config.headers['content-type'] = 'application/json'
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    let res
    if (response.headers.authorization) {
      res = response
    } else {
      res = response.data
    }

    // 此处if-else中设置自己对应的状态码
    // 如果状态码不是200的话，就判断为是错误码
    if (res.code !== 200) {
      MessageBox.confirm(res.code + ': ' + res.msg, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {})
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },

  error => {
    console.log('错误，来自request.js ' + error) // for debug

    Message({
      message: error,
      type: 'error',
      duration: 3 * 1000
    })
    console.log(error)
    return Promise.reject(error)
  }
)

export default service
